package com.ys.peony.utils;

import android.os.Environment;

import com.ys.peony.app.BaseApplication;
import com.ys.peony.app.YSConstant;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileManager {

    private static boolean flag = true;

    /**
     * 保存错误信息
     * @param tag
     * @param e
     */
    public static void saveError(String tag,Exception e){
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
            PrintStream ps = new PrintStream (outStream);
            e.printStackTrace (ps);
            String Stack = outStream.toString ();

            String content = e.getMessage () + "\r\n" + Stack;
            saveLog (tag, content);
        } catch (Exception e1) {
            e1.printStackTrace ();
        }
    }

    /**
     * 保存错误信息
     * @param tag
     * @param content
     */
    public static void saveError(String tag,String content){
        try {
            if (content != null) {
                saveLog (tag, content);
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    /**
     * 日志文件中添加内容
     * 
     * @param content
     * @throws IOException
     */
    public static void saveLog(String Tag,String content){
        if (!flag) { return; }
        BufferedWriter writer = null;
        FileOutputStream logFile = null;
        try {
            String fileName = YSConstant.LOG_FILE;
            File fileDir;
            String parentPath = getParentDirectory ();
            String filePath = parentPath + fileName;
            fileDir = new File (filePath);
            if (fileDir.exists ()) {
                if (fileDir.length () > 128000) {
                    logFile = new FileOutputStream (filePath);
                    logFile.write (new String ("").getBytes ());
                }
            } else {
                fileDir.createNewFile ();
            }
            writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (fileDir,true),System.getProperty ("file.encoding")));
            Date todayNow = new Date ();
            SimpleDateFormat myFmt = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
            String str = "";
            str = myFmt.format (todayNow);
            // 设置写入是内容TAG 标记每个版本能
            writer.write (str + " " + Tag + " " + content + "\r\n");
        } catch (Exception e) {
        } finally {
            try {
                if (logFile != null) logFile.close ();
                if (writer != null) writer.close ();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 日志文件中添加内容
     * @param content
     */
    public static void saveLog(String content){
        try {
            if (content != null) {
                saveLog ("error", content);
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    /**
     * 得到应用存储的根目录
     * @return
     */
    public static String getParentDirectory(){

        String filePath = "";
        String ExternalStorageState = Environment.getExternalStorageState ();

        if (Environment.MEDIA_MOUNTED.equals (ExternalStorageState)) {
            // 日志保存位置
            filePath = Environment.getExternalStorageDirectory ().getPath () + "/" + YSConstant.appName + "/";

        } else { // 找可写的内置SD
            File filetmp = new File ("/mnt");
            File[] subFile = filetmp.listFiles ();
            for ( int i = 0 ; i < subFile.length ; i++ ) {
                if (!subFile[i].isDirectory ()) continue;

                String dirname = subFile[i].getName ();
                if (dirname == null || dirname.length () <= 0) continue;
                if (dirname.indexOf ("sdcard") < 0) continue;

                String path = subFile[i].getAbsolutePath ();
                File file1 = new File (subFile[i].getAbsolutePath () + "/" + YSConstant.appName);
                boolean canWrite = file1.exists ();
                if (!file1.exists ()) canWrite = file1.mkdirs ();
                if (canWrite) {
                    filePath = subFile[i].getAbsolutePath () + "/" + YSConstant.appName + "/";
                    break;
                }
            }

            // 没有sdcard
            if (filePath.length () <= 0) filePath = Environment.getDataDirectory ().getPath () + "/data/" + YSConstant.appName + "/";
        }

        File file = new File (filePath);
        if (!file.exists ()) {
            file.mkdirs ();
        }
        return filePath;
    }

    /**
     * 获取文件存储目录
     *TODO 加入判断存储空间
     * @return
     */
    public static String getFileDirectory(){
        String filePath = "";
        if (Environment.MEDIA_MOUNTED.equals (Environment.getExternalStorageState ())) {
            filePath = Environment.getExternalStorageDirectory ().getPath () + "/" + YSConstant.appName + "/files/";
        } else { // 没有sdcard
            filePath = Environment.getDataDirectory ().getPath () + "/data/" + BaseApplication.getInstance ().getPackageName () + "/files/";
        }
        File file = new File (filePath);
        if (!file.exists ()) {
            file.mkdirs ();
        }
        return filePath;
    }

    /**
     * 获取文件的大小
     * 
     * @param filePath
     * @return
     */
    public static int getFileByte(String filePath){
        File file = null;
        FileInputStream fileInputStream = null;
        int fileSize = 0;
        try {
            file = new File (filePath);
            fileInputStream = new FileInputStream (file);
            fileSize = fileInputStream.available ();
            fileInputStream.close ();
        } catch (Exception e) {
        } finally {
            try {
                if (fileInputStream != null) fileInputStream.close ();
            } catch (IOException e) {

            }
        }
        return fileSize;
    }

    /**
     * 从本地数据中读取
     * 
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String readContent(String fileName) throws IOException{
        StringBuilder sbResult = new StringBuilder ();
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        try {
            String parentPath = getParentDirectory ();
            String filePath = parentPath + fileName;
            File file = new File (filePath);
            read = new InputStreamReader (new FileInputStream (file),"UTF-8");// 考虑到编码格�?
            bufferedReader = new BufferedReader (read);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine ()) != null) {
                sbResult.append (lineTxt);
            }
        } catch (Exception e) {
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close ();
            }
            if (read != null) {
                read.close ();
            }
            return sbResult.toString ();
        }
    }

    /**
     * 把byte数组保存成文件
     * @param data
     * @param length
     * @param filePath
     */
    public static void saveBytesToFile(byte[] data,int length,String filePath){
        ByteArrayOutputStream outPutStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            int lastIndex = filePath.lastIndexOf ("/");
            if (lastIndex > -1) {
                String parentDirectory = filePath.substring (0, lastIndex);
                File file = new File (parentDirectory);
                if (!file.exists ()) {
                    file.mkdirs ();
                }
            }

            fileOutputStream = new FileOutputStream (filePath);
            fileOutputStream.write (data, 0, length);
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        } finally {
            try {
                if (outPutStream != null) {
                    outPutStream.close ();
                }
            } catch (IOException e) {
            }
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close ();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 通过文件名得到byte数组
     * @param filePath
     * @return
     */
    public static byte[] getBytesByName(String filePath){
        byte[] data = null;
        FileInputStream inStream = null;
        ByteArrayOutputStream outStream = null;
        try {
            File file = new File (filePath);
            if (!file.exists ()) { return data; }
            inStream = new FileInputStream (file);
            outStream = new ByteArrayOutputStream ();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read (buffer)) != -1) {
                outStream.write (buffer, 0, len);
            }
            data = outStream.toByteArray ();
        } catch (Exception e) {
        } finally {
            try {
                if (outStream != null) {
                    outStream.close ();
                }
            } catch (IOException e) {
            }
            try {
                if (inStream != null) {
                    inStream.close ();
                }
            } catch (IOException e) {
            }
        }
        return data;
    }

    /**
     * 保存数据到本地
     * 
     * @param fileName
     * @param content
     * @throws IOException
     */
    public static void saveContentToFile(String fileName,String content) throws IOException{
        BufferedWriter writer = null;
        FileOutputStream logFile = null;
        try {
            String parentPath = getParentDirectory ();
            String filePath = parentPath + fileName;
            File file = new File (filePath);
            // if (!file.exists())
            // {
            // file.createNewFile();
            // }
            if (file.exists ())// 文件存在删除以前的文�?
            {
                file.delete ();
            }
            if (!file.exists ()) {
                file.createNewFile ();
            }
            writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (file,true),"utf-8"));
            writer.write (content);
        } catch (Exception e) {
        } finally {
            if (logFile != null) logFile.close ();
            if (writer != null) writer.close ();
        }
    }

    @SuppressWarnings("finally")
    public static String readContentAbsolute(String filePath) throws IOException{
        StringBuilder sbResult = new StringBuilder ();
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        try {
            File file = new File (filePath);
            read = new InputStreamReader (new FileInputStream (file),"UTF-8");// 考虑到编码格�?
            bufferedReader = new BufferedReader (read);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine ()) != null) {
                sbResult.append (lineTxt);
            }
        } catch (Exception e) {
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close ();
            }
            if (read != null) {
                read.close ();
            }
            return sbResult.toString ();
        }
    }

    public static void saveContentToAbsoluteFile(String filePath,String content) throws IOException{
        BufferedWriter writer = null;
        FileOutputStream logFile = null;
        try {
            File file = new File (filePath);
            if (!file.exists ()) {
                file.createNewFile ();
            } else {
                logFile = new FileOutputStream (filePath);
                logFile.write (new String ("").getBytes ());
            }

            writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (file,false),"utf-8"));
            writer.write (content);
        } catch (Exception e) {
        } finally {
            if (logFile != null) logFile.close ();
            if (writer != null) writer.close ();
        }
    }

    /**
     * 得到文件带单位的大小
     * 
     * @param fileSize
     * @return
     */
    public static String getFileSizeStr(long fileSize){
        String result = "";
        int generationIndex = 0;
        float sizeUnit = 1024;
        DecimalFormat df = null;
        df = new DecimalFormat ("#.00");// 格式化小数，不足的补0
        float convertfileSize = fileSize;
        while (convertfileSize > sizeUnit) {
            generationIndex += 1;
            convertfileSize = convertfileSize / sizeUnit;
        }
        result = df.format (convertfileSize);
        switch (generationIndex) {
            case 0:// BYTE
                result += "B";
                break;
            case 1:// KB
                result += "KB";
                break;
            case 2:// MB
                result += "M";
                break;
            case 3: // G
                result += "G";
                break;
            case 4:// PB
                result += "P";
                break;
            case 5:// EB
                result += "E";
                break;
            case 6:// ZB
                result += "Z";
                break;
            case 7: // YB
                result += "Y";
                break;
        }
        return result;
    }

    /**
     * 得到文件的修改时间
     * @param filePath
     * @return
     */
    public static long getFileModifiedTime(String filePath){

        long modifiedTime = 0;
        try {
            File file = new File (filePath);
            if (file.exists ()) {
                modifiedTime = file.lastModified ();
            }
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {

        }

        return modifiedTime;
    }

    /**
     * 设置文件的修改时间
     * @param filePath
     * @param ModifiedTime
     * @return
     */
    public static boolean setFileModifiedTime(String filePath,long ModifiedTime){
        try {
            File file = new File (filePath);
            if (file.exists ()) { return (file.setLastModified (ModifiedTime)); }
        } catch (Exception e) {
            e.printStackTrace ();
        }

        return (false);
    }

    /**
     * 判断该文件是否存在
     * 
     * @param fileName
     * @return
     * @throws Exception
     */
    public static boolean isFileExist(String fileName) throws Exception{
        boolean result = false;
        File file = null;
        try {
            String parentPath = getParentDirectory ();
            String filePath = parentPath + fileName;
            file = new File (filePath);
            if (file.exists ()) {
                result = true;
            }
        } catch (Exception e) {
            result = false;
        }
        return result;
    }

    /**
     * 判断该文件是否存在
     * 
     * @param filePath
     * @return
     * @throws Exception
     */
    public static boolean isAbsoluteFileExist(String filePath) throws Exception{
        boolean result = false;
        File file = null;
        try {
            file = new File (filePath);
            if (file.exists ()) {
                result = true;
            }
        } catch (Exception e) {
            result = false;
        }
        return result;
    }

    /**
     * 删除文件
     */
    public static boolean delete(){
        try {
            String filePath = getParentDirectory ();
            // 如果sPath不以文件分隔符结尾，自动添加文件分隔
            if (!filePath.endsWith (File.separator)) {
                filePath = filePath + File.separator;
            }
            File dirFile = new File (filePath);
            // 如果dir对应的文件不存在，或者不是一个目录，�?
            if (!dirFile.exists () || !dirFile.isDirectory ()) { return false; }
            boolean flag = true;
            // 删除文件夹下的所有文件包括子目录
            File[] files = dirFile.listFiles ();
            for ( int i = 0 ; i < files.length ; i++ ) {
                if (files[i].isFile ()) {
                    flag = delete (files[i].getAbsolutePath ());
                    if (!flag) break;
                }
            }
            if (!flag) return false;
            // 删除当前目录
            if (dirFile.delete ()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
        }
        return true;
    }

    /**
     * 删除文件目录
     */
    public static boolean delete(String absoluteFilePath){
        boolean result = false;
        try {
            File file = new File (absoluteFilePath);
            result = file.delete ();
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 删除文件目录
     * @param file
     * @return
     */
    public static boolean deleteFile(File file){
        if (file.exists ()) { // 判断文件是否存在
            if (file.isFile ()) { // 判断是否是文件
                file.delete (); //
            } else if (file.isDirectory ()) { 
                File files[] = file.listFiles (); // 声明目录下所有的文件 files[];
                for ( int i = 0 ; i < files.length ; i++ ) { // 遍历目录下所有的文件
                    deleteFile (files[i]); // 
                }
            }
            file.delete ();
            return true;
        } else {
            return false;
        }
    }

}
